import React, { useEffect, useState } from "react"
import { useHistory } from 'react-router-dom'
import {
  Input,
  InputGroup,
  Stack,
  InputLeftAddon,
  Button,
  FormControl,
  Flex,
  Checkbox,
  Text,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverBody,
  List,
  ListItem,
  Link,
  PopoverArrow,
  useToast
} from "@chakra-ui/react"
import { FaUserAlt, FaLock } from "react-icons/fa"
import { Formik, Form, Field } from "formik"
import axios from "axios"

export default function SignIn() {
  const toast = useToast()
  const history = useHistory()
  const [isLoading, setIsLoading] = useState(false)
  const [isRememberMe, setIsRememberMe] = useState(false)
  const initialValues = {
    email: localStorage.getItem('isRememberMe') || '',
    password: ''
  }
  const handleSubmit = values => {
    if (values.email === '' || values.password === '') {
      toast({
        title: '手机号、邮箱或者密码不能为空',
        status: 'error',
        position: 'top',
        isClosable: true,
      })
    } else {
      setIsLoading(true)
      axios.post('https://conduit.productionready.io/api/users/login', {
        user: {
          ...values
        }
      }).then(res => {
        setIsLoading(false)
        if (res.status === 200) {
          toast({
            title: '登录成功',
            status: 'success',
            position: 'top',
            isClosable: true
          })
          localStorage.setItem('userInfo', JSON.stringify(res.data))
          if (isRememberMe) {
            localStorage.setItem('isRememberMe', res.data.user.email)
          } else {
            localStorage.removeItem('isRememberMe')
          }
          history.push('/')
        }
      }).catch(err => {
        setIsLoading(false)
        err && toast({
          title: '用户名或者密码错误',
          status: 'error',
          position: 'top',
          isClosable: true,
        })
      })
    }
  }

  const handleToggleIsRememberMe = e => {
    setIsRememberMe(e.target.checked)
  }

  useEffect(() => {
    const isRememberMe = localStorage.getItem('isRememberMe')
    if (isRememberMe) {
      setIsRememberMe(true)
    }
  }, [])

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
    >
      <Form>
        <Stack spacing="4" w="100%">
          <Stack spacing="0" w="100%">
            <Field name="email">
              {({ field, form }) => (
                <FormControl>
                  <InputGroup bgColor="#F7F7F7">
                    <InputLeftAddon
                      children={<FaUserAlt />}
                      color="#969696"
                      borderBottom="none"
                      bg="none"
                      borderColor="#c8c8c8"
                      borderBottomLeftRadius="0"
                    />
                    <Input
                      {...field}
                      placeholder="手机号或邮箱"
                      borderBottom="none"
                      borderLeft="none"
                      bg="none"
                      fontSize="14px"
                      paddingLeft="0"
                      borderColor="#c8c8c8"
                      borderBottomRightRadius="0"
                      _placeholder={{ color: "#969696" }}
                      _focus={{ boxShadow: "none" }}
                    />
                  </InputGroup>
                </FormControl>
              )}
            </Field>
            <Field name="password">
              {({ field, form }) => (
                <FormControl>
                  <InputGroup bgColor="#F7F7F7">
                    <InputLeftAddon
                      children={<FaLock />}
                      color="#969696"
                      bg="none"
                      borderColor="#c8c8c8"
                      borderTopLeftRadius="0"
                    />
                    <Input
                      {...field}
                      type="password"
                      placeholder="密码"
                      autoComplete="new-password"
                      borderLeft="none"
                      bg="none"
                      fontSize="14px"
                      paddingLeft="0"
                      borderTopRightRadius="0"
                      borderColor="#c8c8c8"
                      _placeholder={{ color: "#969696" }}
                      _focus={{ boxShadow: "none" }}
                    />
                  </InputGroup>
                </FormControl>
              )}
            </Field>
          </Stack>
          <Flex align="center" justifyContent="space-between" w="100%" mt="10px" fontSize="14px">
            <Checkbox
              color="#969696"
              _focus={{ boxShadow: "none" }}
              isChecked={isRememberMe}
              onChange={handleToggleIsRememberMe}
            >记住我</Checkbox>
            <Popover>
              <PopoverTrigger>
                <Text color="#999" fontSize="14px" cursor="pointer">登录遇到问题？</Text>
              </PopoverTrigger>
              <PopoverContent>
                <PopoverArrow />
                <PopoverBody>
                  <List fontSize="14px">
                    <Stack spacing="2">
                      <ListItem><Link href="https://www.jianshu.com/users/password/mobile_reset" isExternal _hover={{textDecoration: "none"}} _focus={{boxShadow: "none"}}>用手机号重置密码</Link></ListItem>
                      <ListItem><Link href="https://www.jianshu.com/users/password/email_reset" isExternal _hover={{textDecoration: "none"}}>用邮箱重置密码</Link></ListItem>
                      <ListItem><Link href="https://www.jianshu.com/p/9058d0b8711d" isExternal _hover={{textDecoration: "none"}}>无法用海外手机号登录</Link></ListItem>
                      <ListItem><Link href="https://www.jianshu.com/p/498a9fa7da08" isExternal _hover={{textDecoration: "none"}}>无法用 Google 帐号登录</Link></ListItem>
                    </Stack>
                  </List>
                </PopoverBody>
              </PopoverContent>
            </Popover>
          </Flex>
          <Button
            type="submit"
            w="100%"
            color="#fff"
            bgColor="#3194d0"
            borderRadius="25px"
            _hover={{ bgColor: "#187cb7" }}
            _focus={{ boxShadow: "none" }}
            isLoading={isLoading}
            loadingText="登录中..."
          >
            登录
          </Button>
        </Stack>
      </Form>
    </Formik>
  );
}
